//
//  specialChannelTC.swift
//  甜言蜜语
//
//  Created by yingli_yanfa_liuxingyu on 16/7/27.
//  Copyright © 2016年 wl. All rights reserved.
//

import UIKit
import SVProgressHUD
class specialChannelTC: UITableViewController, HeardDelegate, signDelegate {
   
    /// 当前频道
    var channel: String!
    /// 当前频道的url
    var channelUrl: String!
    
    @IBOutlet weak var starBtn: UIButton!
    @IBOutlet weak var specialBtn: UIButton!
    
    var starPage = 0
    var spectialPage = 0
    var selectedStarPage = 0
    var selectedSpectialPage = 0
    var starModelList: [starBusinessInfo]!{
        didSet {
            self.tableView.reloadData()
        }

    }
    var specialModelList: [specialProductInfo]!{
        didSet {
            self.tableView.reloadData()
        }
    }
    //签到视图
    var signView: Sign?
    var SignModel: signModel?
    var msg: regiestInfo?
    var isSelected: Bool?//是否选择了某个按钮
    var isClickedStar: Bool?//是否选择了明星按钮
    var isClickedSpecial: Bool?//是否选了了专业按钮
    var hasSelectedStar: Bool = false//是否选择了下拉菜单
    var hasSelectedSpectail: Bool = false//是否选择了下拉菜单
    
    var newsTableHeadViewController = NewsHeadViewController()
    var fontSize: CGFloat!
    override func viewDidLoad() {
        super.viewDidLoad()

        isSelected = false
        isClickedStar = false
        isClickedSpecial = false
        self.starBtn.layer.masksToBounds = true
        self.starBtn.layer.borderWidth = 2
        self.specialBtn.layer.masksToBounds = true
        self.specialBtn.layer.borderWidth = 2
        
        
        publicMethod.setHUDStyle()
        self.newsTableHeadViewController.url = self.channelUrl
        
        self.addChildViewController(self.newsTableHeadViewController)
        self.tableView.tableHeaderView = self.newsTableHeadViewController.view
        
        self.newsTableHeadViewController.delegate = self
        
        self.tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(requestInfo))
        
        self.tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(specialChannelTC.nextRequestInfo))
        self.tableView.mj_header.beginRefreshing()

    }
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
        
        self.channelUrl = "zyyx"
        
        
    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        if ApplicationDelegate.isLogin(){
            let phone = publicMethod.userName()
            let pass = publicMethod.passWord()
            let token = publicMethod.token()
            DataTool.login(phone, pass: pass, token: token, completionHandler: { (newModel) in
                guard let newDataes = newModel else {
                    return
                }
                print(newDataes)
                
            })
            
        }
        
        isSelected = false
        isClickedStar = false
        isClickedSpecial = false
        self.starBtn.hidden = false
        self.specialBtn.hidden = false
        self.starBtn.layer.masksToBounds = true
        self.starBtn.layer.borderWidth = 2
        self.specialBtn.layer.masksToBounds = true
        self.specialBtn.layer.borderWidth = 2
        
        self.newsTableHeadViewController.url = self.channelUrl
        
        self.addChildViewController(self.newsTableHeadViewController)
        self.tableView.tableHeaderView = self.newsTableHeadViewController.view
        
        self.newsTableHeadViewController.delegate = self
        
        //字体大小
        let str = ApplicationDelegate.fontSize()
        self.fontSize  =  CGFloat ( (str as NSString).floatValue)
        
        self.starBtn.titleLabel?.font = UIFont.systemFontOfSize(self.fontSize)
        self.specialBtn.titleLabel?.font = UIFont.systemFontOfSize(self.fontSize)
        self.tabBarController?.tabBar.hidden = false
        self.tableView.reloadData()

    }
   
    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if isSelected == true {
            if(isClickedStar == true){
                let count = self.starModelList.count
                return count
                
            }else if (isClickedSpecial == true){
                let count = self.specialModelList.count
                return count
            }
        }
        return 0
    }
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if(cell.respondsToSelector(Selector("setSeparatorInset:"))) {
            cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)
        }
        if(cell.respondsToSelector(Selector("setLayoutMargins:"))) {
            cell.layoutMargins = UIEdgeInsetsMake(0, 0, 0, 0)
        }
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        if isSelected == true{
            if isClickedStar == true{
                return 115.0
            }else if isClickedSpecial == true{
                 let model = specialModelList[indexPath.row]
                if model.imgType != 0 && model.imgType > 0{
                    return 200.0
                }else if model.imgextra != nil{
                    return 107.0
                }else{
                    return 95.0
                }
            }
        }
        return 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        if isSelected == true && isClickedStar == true{
            let cell = tableView.dequeueReusableCellWithIdentifier("specialChannelCell", forIndexPath: indexPath) as! specialChannelCell
            let model = starModelList[indexPath.row]

            cell.iv.sd_setImageWithURL(NSURL(string: model.timg), placeholderImage: UIImage(named: "placeholder"))
            cell.addressLbl.text = String(format: "%@%@%@",model.unitaddress ,model.unitarea ,model.unittype)
            cell.addressLbl.font = UIFont.systemFontOfSize(self.fontSize - 2)
            cell.id = model.id
            cell.intruductLbl.text = model.introduction
            cell.intruductLbl.font = UIFont.systemFontOfSize(self.fontSize - 2)
            cell.titleLbl.text = model.unitname
            cell.titleLbl.font = UIFont.systemFontOfSize(self.fontSize)
            cell.levelLbl.text = model.reputation
            if model.reputation == "金牌企业"{
                cell.levelLbl.backgroundColor = UIColor.yellowColor()
            }
            //
            return cell
        } else  {
            // Configure the cell...
            let model = specialModelList[indexPath.row]
            if model.imgType != 0 && model.imgType > 0{
                let cell = tableView.dequeueReusableCellWithIdentifier("specialBigPictureCell", forIndexPath: indexPath) as! specialBigPictureCell//大图显示
                cell.titleLbl.text = model.name
                cell.titleLbl.font = UIFont.systemFontOfSize(self.fontSize)
                
            cell.iv.sd_setImageWithURL(NSURL(string: model.imgsrc), placeholderImage: UIImage(named: "placeholder"))
                cell.levelLbl.text = model.reputation
                if model.reputation == "金牌企业"{
                    
                   cell.levelLbl.backgroundColor = UIColor.yellowColor()
                }
                return cell

            }
            if  model.imgextra != nil{
                let cell = tableView.dequeueReusableCellWithIdentifier("specialThreePictureCell", forIndexPath: indexPath) as! specialThreePictureCell//三张图显示
                cell.titleLbl.text = model.name
                cell.titleLbl.font = UIFont.systemFontOfSize(self.fontSize)
                cell.iv1.sd_setImageWithURL(NSURL(string: model.imgextra![0]), placeholderImage: UIImage(named: "placeholder"))
                cell.iv2.sd_setImageWithURL(NSURL(string: model.imgextra![1]), placeholderImage: UIImage(named: "placeholder"))
                cell.iv3.sd_setImageWithURL(NSURL(string: (model.imgextra?[2])!), placeholderImage: UIImage(named: "placeholder"))
                cell.levelLbl.text = model.reputation
                if model.reputation == "金牌企业"{
                    
                   cell.levelLbl.backgroundColor = UIColor.yellowColor()
                }
                return cell
                
            }else{
                let cell = tableView.dequeueReusableCellWithIdentifier("specialNormalCell", forIndexPath: indexPath) as! specialNormalCell//普通显示
                    cell.titleLbl.text = model.name
                cell.titleLbl.font = UIFont.systemFontOfSize(self.fontSize)
                    cell.iv.sd_setImageWithURL(NSURL(string: model.imgsrc), placeholderImage: UIImage(named: "placeholder"))
                
                cell.levelLbl.text = model.reputation
                if model.reputation == "金牌企业"{
                    cell.levelLbl.backgroundColor = UIColor.yellowColor()

                }
                return cell
            }
        }
    }
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
       tableView.deselectRowAtIndexPath(indexPath, animated: true)
        
        if isSelected == true && isClickedStar == true{
            let vc = self.storyboard?.instantiateViewControllerWithIdentifier("SpecialStarDetailVC") as! SpecialStarDetailVC
            vc.id = self.starModelList[indexPath.row].id
            self.navigationController?.pushViewController(vc, animated: true)
            
        }else{
            let vc = self.storyboard?.instantiateViewControllerWithIdentifier("SpectailDetail") as! SpectailDetail
            vc.id = self.specialModelList[indexPath.row].id
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
    }

   @IBAction func statBtnSelecte(sender: UIButton) -> Void {
        isSelected = true
        isClickedStar = true
        self.starBtn.hidden = true
        self.specialBtn.hidden = true
        self.channelUrl = "mxqy"
        self.newsTableHeadViewController.url = self.channelUrl
        self.tableView.tableHeaderView = self.newsTableHeadViewController.view
        
        self.newsTableHeadViewController.delegate = self
         self.newsTableHeadViewController.initDropDownMenu()
        self.tableView.mj_header.beginRefreshing()
    }
    
   @IBAction func specialBtnSelecte(sender: UIButton) -> Void {
       isSelected = true
       isClickedSpecial = true
       self.specialBtn.hidden = true
       self.starBtn.hidden = true
       self.channelUrl = "zycp"
       self.newsTableHeadViewController.url = self.channelUrl
       self.tableView.tableHeaderView = self.newsTableHeadViewController.view
       self.newsTableHeadViewController.initDropDownMenu()
       self.newsTableHeadViewController.delegate = self
    


       self.tableView.mj_header.beginRefreshing()
    }
    //MARK:search
    func searchClick() -> Void {
        print("搜索")
        let sb = (UIStoryboard.init(name: "Search", bundle: nil))
        let vc = (sb.instantiateViewControllerWithIdentifier("SearchViewController"))
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    
   

    func signClick(sender: UIButton) -> Void {
        //应该调接口
        let btn: UIButton = sender
        btn.selected = !btn.selected
        if btn.selected{
            print("签到")
            if ApplicationDelegate.isLogin(){
                self.tableView.setContentOffset(CGPointMake(0, 0), animated: false)
                self.checkInSign()
                signView = Sign.init(frame: kScreen_frame)
                signView?.delegate = self
                
                self.view.addSubview(signView!)
            }else{
                let sb = UIStoryboard(name: "Login", bundle: nil)
                let vc = sb.instantiateViewControllerWithIdentifier("LoginViewController")
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }else{
            signView?.closeBtnClick()
        }
     
       
        
    }
       //MARK:signViewDelegate
    func signBtnClicked(sender: UIButton){
        //调接口
        self.signSelected()
        
    }
    //MARK:NWTWORKING
    func checkInSign(){
        DataTool.signInfo({ (newModel) in
            guard newModel != nil else {
                return
            }
            self.SignModel = newModel
            self.signView!.model = self.SignModel
        })
    }
    
    func signSelected(){
        DataTool.sign({ (newModel) in
            guard newModel != nil else {
                return
            }
            self.msg = newModel
            self.checkInSign()
            SVProgressHUD.showSuccessWithStatus(self.msg?.msg)
           
        })
    }
    
    // MARK: - HeardDelegate
    func onHeightChange(newView: UIView) {
        self.tableView.tableHeaderView = newView
    }
    func setContentViewControllerWithInfo(cellInfo: [NewsModel]? ) -> Void{
        
    }
    func setContentTransferViewControllerWithInfo(cellInfo: [TransferModel]?) -> Void{
        
    }
    func setContentJoninUsViewControllerWithInfo(cellInfo: [JoinUsModel]?) -> Void{
        
    }
    func setContentMXQYViewConreollerWithInfo(cellInfo: [starBusinessInfo]?) -> Void{
        self.starModelList = cellInfo
        self.hasSelectedStar = true
    }
    func setContentZYCPViewControllerWithInfo(cellInfo: [specialProductInfo]?) -> Void{
        
        self.specialModelList = cellInfo
        self.hasSelectedSpectail = true
    }
    
    func CyclePictureViewSelected(){
        let vc = self.storyboard?.instantiateViewControllerWithIdentifier("DetailTaoboaAndliveVideoVC") as! DetailTaoboaAndliveVideoVC
        
        vc.urlStr = "https://www.taobao.com"
        
        self.navigationController?.pushViewController(vc, animated: true)
    }
       /**
     下拉刷新，加载最新数据
     */
    func requestInfo() {
        if isSelected == true{
            if isClickedStar == true{
                if hasSelectedStar == false{
                    self.starPage = 0
                    DataTool.starBusiness({ (newModel) in
                        self.tableView.mj_header.endRefreshing()
                        guard let newDataes = newModel else {
                            return
                        }
                        print(newDataes)
                        self.starModelList = newDataes
                        
                    })
                }else{
                    self.selectedStarPage = 0
                    DataTool.dropMenuScreen_mxqy(self.newsTableHeadViewController.membertypecn!, hyfl: self.newsTableHeadViewController.hyfl!, reputation: self.newsTableHeadViewController.reputation!,page: String(self.selectedStarPage),completionHandler: { (newsArray) -> Void in
                        self.tableView.mj_header.endRefreshing()
                        guard let newDataes = newsArray else {
                            return
                        }
                        print(newDataes)
                        self.starModelList = newDataes

                    })

                }
                
            }else if isClickedSpecial == true{
                if hasSelectedSpectail == false{
                    self.spectialPage = 0
                    DataTool.specialProduct({ (newModel) in
                        self.tableView.mj_header.endRefreshing()
                        guard let newDataes = newModel else {
                            return
                        }
                        print(newDataes)
                        self.specialModelList = newDataes
                        
                    })
                }else{
                    self.selectedSpectialPage = 0
                    DataTool.dropMenuScreen_zycp(self.newsTableHeadViewController.productTags!, reputation: self.newsTableHeadViewController.productReputation!, paixu: self.newsTableHeadViewController.productPaixu!,page: String(self.selectedSpectialPage), completionHandler: { (newsArray) -> Void in
                        self.tableView.mj_header.endRefreshing()
                        guard let newDataes = newsArray else {
                            return
                        }
                        print(newDataes)
                        self.specialModelList = newDataes
                    })
                }
               
            }
           
        }else{
             self.tableView.mj_header.endRefreshing()
        }
        
    }
    //上拉刷新
    func nextRequestInfo(){
        if isSelected == true{
            if isClickedStar == true{
                self.starPage += 1
               
                let urlStr = String(format: "%@user/mxqy/fenye/\(self.starPage)",BaseUrl)
                
                DataTool.starNextBusiness(String(self.starPage), urlStr: urlStr, completionHandler: { (newModel) in
                    self.tableView.mj_footer.endRefreshing()
                    guard let newDataes = newModel else {
                        return
                    }
                    print(newDataes)
                    self.starModelList! += newDataes
                    
                })
                
        }else{
                self.spectialPage += 1
               
                let urlStr = String(format: "%@brand/dosel/fenye/\(self.spectialPage)", BaseUrl)
                DataTool.specialNextProduct(String(self.spectialPage), urlStr: urlStr,completionHandler: { (newModel) in
                    self.tableView.mj_footer.endRefreshing()
                    guard let newDataes = newModel else {
                        return
                    }
                    print(newDataes)
                    self.specialModelList! += newDataes
                    
                })
            }
        }
    }
  
   
    
}


